//
//  YAYISystemInfoController.m
//  yayi
//
//  Created by hxp on 16/4/28.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYISystemInfoController.h"

#import "YAYISystemMessageCell.h"
#import "YAYIBookMessageCell.h"
#import "YAYIPerfectMessageCell.h"
#import "YAYIMsgDetailController.h"
#import "YAYIMessageListModel.h"

@interface YAYISystemInfoController ()

@property (nonatomic, weak) UILabel *noDataFlagLbl;

@property (nonatomic, strong) NSMutableArray *messageArray;

/** 分页相关 */
@property (nonatomic, assign) NSInteger curPage;
@property (nonatomic, assign) NSInteger pageCount;

@end


@implementation YAYISystemInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray *titleArray = @[@"系统通知", @"预约通知", @"雅同精选"];
    self.title = titleArray[self.type - 1];
    self.view.backgroundColor = [UIColor colorWithWhite:0.965 alpha:1];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 20, 0);
    
    self.messageArray = [NSMutableArray array];
    
    
//    [self getMessageList];
    
    __block typeof(self) weakself = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [weakself getMessageList];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [weakself getMoreMessageList];
    }];
//    [self.tableView.mj_footer setAutomaticallyHidden:YES];

    [self.tableView.mj_header beginRefreshing];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"PageOne"];//("PageOne"为页面名称，可自定义)
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"PageOne"];
}


/**
 *  没有数据时显示
 */
- (void)showNoDataFlag:(BOOL)flag
{
    if (!flag) {
        [self.noDataFlagLbl removeFromSuperview];
        self.noDataFlagLbl = nil;
        return;
    }
    
    if (self.noDataFlagLbl) {
        return;
    }
    UILabel *flagLbl = [[UILabel alloc] init];
    flagLbl.text = @"暂时没有消息";
    flagLbl.font = [UIFont systemFontOfSize:17];
    flagLbl.textColor = YAYIColor(107, 178, 242);
    flagLbl.textAlignment = NSTextAlignmentCenter;
    [self.tableView addSubview:flagLbl];
    self.noDataFlagLbl = flagLbl;
    [flagLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView);
        make.centerY.equalTo(self.tableView).offset(-50);
    }];
}


#pragma mark - 获取数据
- (void)getMessageList
{
    
    [self.messageArray removeAllObjects];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"type"] = @(self.type);
    param[@"currentpage"] = @(1);
    
    YAYILog(@"param:%@", param);
    
    [YAYINetWorking getWithURL:messageList_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                
                [self.tableView.mj_header endRefreshing];
            }else{
                
                NSArray *dictArray = dict[@"data"];
                
                for (NSDictionary *dictItem in dictArray) {
                    YAYIMessageListModel *model = [[YAYIMessageListModel alloc] init];
                    [model setValuesForKeysWithDictionary:dictItem];
//                    model.title = @"消息消息细搜啊发动机离开讲道理就了的空间了发动机六块腹肌快到家了看角度看解放路口见可浪费就冷风机来看积分来看看九分裤了积分卡讲课费看2016-08-25 13:00:00";
                    [self.messageArray addObject:model];
                }
                self.curPage = 1;
                
                [self.tableView.mj_header endRefreshing];
                if (self.messageArray.count < 10) {
                    [self.tableView.mj_footer endRefreshing];
                    [self.tableView.mj_footer setHidden:YES];
                }else{
                    self.tableView.mj_footer.hidden = NO;
                    [self.tableView.mj_footer setState:MJRefreshStateIdle];
                }
            }
        }else{
        
            [self.tableView.mj_header endRefreshing];
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:nil];
            YAYILog(@"error：%@", dict);
        }
        
        if (0 == self.messageArray.count) {
            [self showNoDataFlag:YES];
        }else{
            [self showNoDataFlag:NO];
        }
        
        [self.tableView reloadData];
        
    }];
}


- (void)getMoreMessageList
{
    self.curPage++;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"type"] = @(self.type);
    param[@"currentpage"] = @(self.curPage);
    
    YAYILog(@"param:%@", param);
    
    [YAYINetWorking getWithURL:messageList_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                
                return;
            }else{
                
                NSArray *dictArray = dict[@"data"];
                
                for (NSDictionary *dictItem in dictArray) {
                    YAYIMessageListModel *model = [[YAYIMessageListModel alloc] init];
                    [model setValuesForKeysWithDictionary:dictItem];
                    
                    [self.messageArray addObject:model];
                }
                
                if (dictArray.count < 10) {
                    [self.tableView.mj_footer endRefreshing];
                    self.tableView.mj_footer.hidden = YES;
                }else{
                    [self.tableView.mj_footer endRefreshing];
                }
                
                [self.tableView reloadData];
            }
        }else{
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:nil];
            YAYILog(@"error：%@", dict);
        }
    }];
}


#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (3 == self.type) {
        
        YAYIMessageListModel *model = self.messageArray[indexPath.row];
        CGFloat height1 = [self heightForRow:model.title font:[UIFont systemFontOfSize:15] width:SCREEN_width - 34 * 2];
        CGFloat height2 = [self heightForRow:model.brief font:[UIFont systemFontOfSize:14] width:SCREEN_width - 34 * 2];
        CGFloat cellH = 50 + height1 + height2 + 15 * 3 + 38;
        if (model.picurl && ![model.picurl isKindOfClass:[NSNull class]]) {
            cellH += 278 * YAYIScreenScale + 15;
        }
        return cellH;
    }else{
    
        YAYIMessageListModel *model = self.messageArray[indexPath.row];
//        CGFloat height2 = [self heightForRow:model.title font:[UIFont systemFontOfSize:14] width:SCREEN_width - 34 * 2];
        CGFloat height2 = [model.title sizewithFont:[UIFont systemFontOfSize:14]  maxSize:CGSizeMake(SCREEN_width - 34 * 2, MAXFLOAT)].height;
        return 18 + 25 + 80 + height2;
    }
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.messageArray.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    YAYIMessageListModel *model = self.messageArray[indexPath.row];
    
    if (1 == self.type) {
        
        YAYISystemMessageCell *cell = [YAYISystemMessageCell cellWith:tableView];
        cell.model = model;
        
        
        return cell;
    }else if (2 == self.type){
        
        YAYIBookMessageCell *cell = [YAYIBookMessageCell cellWith:tableView];
        cell.model = model;
        
        return cell;
    }else if (3 == self.type){
        
        YAYIPerfectMessageCell *cell = [YAYIPerfectMessageCell cellWith:tableView];
        cell.model = model;

        return cell;
    }
    
    return nil;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    YAYIMessageListModel *model = self.messageArray[indexPath.row];
    
//    YAYIMsgDetailController *detaileView = [YAYIMsgDetailController new];
//    [self.navigationController pushViewController:detaileView animated:YES];
}


-(CGFloat)heightForRow:(NSString *)str font:(UIFont *)font width:(CGFloat)width
{
    CGSize size = [str sizeWithFont:font constrainedToSize:CGSizeMake(width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
    return size.height;
}


@end
